/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Filters;

import Facebook.FacebookClientLocal;
import com.sun.jersey.core.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.CreateException;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import org.json.JSONException;
import org.json.JSONObject;
import smartgrid.FacebookAccountInterface;
import smartgrid.exceptions.FacebookAccountDisabledException;

/**
 *
 * @author andre
 */
public class SmartPhaseListener implements PhaseListener {

    @Override
    public void afterPhase(PhaseEvent event) {
        
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        
        if(request.getRequestURI().contains("backOffice"))
            return;
        
        FacebookClientLocal fbl = null;
        if (request != null) {
            fbl = (FacebookClientLocal) request.getSession(true).getAttribute("facebook");
        }

        if (fbl == null) {
            // Validate the signed request
            String signed_request = (String) request.getParameter("signed_request");
            if (signed_request == null) {
                NavigationHandler nh = FacesContext.getCurrentInstance().getApplication().getNavigationHandler();
                nh.handleNavigation(FacesContext.getCurrentInstance(), null, "login");
            } else {
                int i = signed_request.indexOf('.');
                String json = signed_request.substring(i + 1);
                json = new String(Base64.decode(json));

                try {
                    JSONObject jso = new JSONObject(json);
                    if (jso.has("user_id")) {
                        InitialContext initCtx = new InitialContext();
                        fbl = (FacebookClientLocal) initCtx.lookup("java:global/SmartGridEA/FacebookClient");

                        FacebookClientLocal fb = fbl.create();

                        fb.setOAuthInfo(jso.getString("oauth_token"), jso.getString("user_id"));
                        fb.setUserInfo();
                        request.getSession().setAttribute("facebook", fb);
                        
                        FacebookAccountInterface fbm = (FacebookAccountInterface)initCtx.lookup("java:global/SmartGridEA/FacebookAccountManager");
                        try {
                            if(!fbm.facebookAccountHasContracts(fb.getUId())){
                                NavigationHandler nh = FacesContext.getCurrentInstance().getApplication().getNavigationHandler();
                                nh.handleNavigation(FacesContext.getCurrentInstance(), null, "unregistered");
                            }
                        } catch (FacebookAccountDisabledException ex) {
                            Logger.getLogger(SmartPhaseListener.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        NavigationHandler nh = FacesContext.getCurrentInstance().getApplication().getNavigationHandler();
                        nh.handleNavigation(FacesContext.getCurrentInstance(), null, "login");
                    }

                } catch (CreateException ex) {
                    Logger.getLogger(SmartPhaseListener.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NamingException ex) {
                    Logger.getLogger(SmartPhaseListener.class.getName()).log(Level.SEVERE, null, ex);
                } catch (JSONException ex) {
                    NavigationHandler nh = FacesContext.getCurrentInstance().getApplication().getNavigationHandler();
                    nh.handleNavigation(FacesContext.getCurrentInstance(), null, "login");
                }
            }
        } else{
            System.out.println(fbl.getUserFriendsJson());
            try {
                InitialContext initCtx = new InitialContext();
                FacebookAccountInterface fbm = (FacebookAccountInterface)initCtx.lookup("java:global/SmartGridEA/FacebookAccountManager");
                try {
                    if(request.getParameter("contractform") == null && !fbm.facebookAccountHasContracts(fbl.getUId())){
                        NavigationHandler nh = FacesContext.getCurrentInstance().getApplication().getNavigationHandler();
                        nh.handleNavigation(FacesContext.getCurrentInstance(), null, "unregistered");
                    }
                } catch (FacebookAccountDisabledException ex) {
                    Logger.getLogger(SmartPhaseListener.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (NamingException ex) {
                Logger.getLogger(SmartPhaseListener.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void beforePhase(PhaseEvent event) {
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
}
